<template>
  <div ref="chartContainer" class="chart-container" :style="{ height }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

// 定义组件属性
interface Props {
  options: echarts.EChartsOption
  height?: string
}

const props = withDefaults(defineProps<Props>(), {
  height: '400px'
})

// 图表容器引用
const chartContainer = ref<HTMLDivElement | null>(null)
let chart: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (chartContainer.value) {
    chart = echarts.init(chartContainer.value)
    chart.setOption(props.options)
  }
}

// 重新调整图表大小
const resizeChart = () => {
  chart?.resize()
}

// 监听选项变化并更新图表
watch(
  () => props.options,
  () => {
    if (chart) {
      chart.setOption(props.options, true) // true 表示不合并选项
    }
  },
  { deep: true }
)

// 组件挂载时初始化图表
onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

// 组件卸载前清理
onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
  chart?.dispose()
})

// 定义组件暴露的方法
defineExpose({
  resize: resizeChart
})
</script>

<style scoped>
.chart-container {
  width: 100%;
}
</style>